﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CodeTester
{
    public class TaskLearn
    {

        public void TaskUse()
        {
            Task t = new Task(() =>
            {
                Console.WriteLine("任务开始工作……");
                //模拟工作过程
                Thread.Sleep(5000);
            });
            t.Start();
            t.ContinueWith((tt) =>             
            {
                Console.WriteLine("任务完成，完成时候的状态为：");
                Console.WriteLine("IsCanceled={0}\tIsCompleted={1}\tIsFaulted={2}", tt.IsCanceled, tt.IsCompleted, tt.IsFaulted);
            }
                
            );
            Console.ReadKey();
        }


        public void  TaskUse2()
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            Task<int> t = new Task<int>(() => Add(cts.Token));
            t.Start();
            t.ContinueWith(TaskEnded);
            //等待按下任意一个键取消任务
            Console.ReadKey();
            cts.Cancel();
            Console.ReadKey();
        }

        void TaskEnded(Task<int> task)
        {
            Console.WriteLine("任务完成，完成时候的状态为：");
            Console.WriteLine("IsCanceled={0}\tIsCompleted={1}\tIsFaulted={2}", task.IsCanceled, task.IsCompleted, task.IsFaulted);
            Console.WriteLine("任务的返回值为：{0}", task.Result);
        }

        int Add(CancellationToken ct)
        {
            Console.WriteLine("任务开始……");
            int result = 0;
            while (!ct.IsCancellationRequested)
            {
                result++;
                Thread.Sleep(1000);
            }
            return result;
        }



        public void TaskFactory()
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            TaskFactory tf = new TaskFactory();

            tf.StartNew(() => Add(cts.Token));
            Console.ReadKey();
            cts.Cancel();
            Console.ReadKey();
        }


        public async Task<long>  TestAsync(uint n)
        {
            Console.WriteLine("TestAsync Begin");
            long a =await Task<long>.Run(() => { return new FibonacciRecursively().Fibonacci(n); });
            Console.WriteLine("TestAsync Begin");
            return a;
        }


    }
}
